home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16.lha / Python-1.6 / Lib / Python1.6 / distutils / msvccompiler.py < prev    next >
Encoding:
Python Source  |  2000-08-04  |  16.8 KB  |  496 lines

  1. """distutils.msvccompiler
  2.  
  3. Contains MSVCCompiler, an implementation of the abstract CCompiler class
  4. for the Microsoft Visual Studio."""
  5.  
  6.  
  7. # created 1999/08/19, Perry Stoll
  8. # hacked by Robin Becker and Thomas Heller to do a better job of
  9. #   finding DevStudio (through the registry)
  10.  
  11. __revision__ = "$Id: msvccompiler.py,v 1.38 2000/08/04 01:29:27 gward Exp $"
  12.  
  13. import sys, os, string
  14. from types import *
  15. from distutils.errors import \
  16.      DistutilsExecError, DistutilsPlatformError, \
  17.      CompileError, LibError, LinkError
  18. from distutils.ccompiler import \
  19.      CCompiler, gen_preprocess_options, gen_lib_options
  20.  
  21. _can_read_reg = 0
  22. try:
  23.     import _winreg
  24.  
  25.     _can_read_reg = 1
  26.     hkey_mod = _winreg
  27.  
  28.     RegOpenKeyEx = _winreg.OpenKeyEx
  29.     RegEnumKey = _winreg.EnumKey
  30.     RegEnumValue = _winreg.EnumValue
  31.     RegError = _winreg.error
  32.  
  33. except ImportError:
  34.     try:
  35.         import win32api
  36.         import win32con
  37.         _can_read_reg = 1
  38.         hkey_mod = win32con
  39.  
  40.         RegOpenKeyEx = win32api.RegOpenKeyEx
  41.         RegEnumKey = win32api.RegEnumKey
  42.         RegEnumValue = win32api.RegEnumValue
  43.         RegError = win32api.error
  44.  
  45.     except ImportError:
  46.         pass
  47.  
  48. if _can_read_reg:
  49.     HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT
  50.     HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE
  51.     HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER
  52.     HKEY_USERS = hkey_mod.HKEY_USERS
  53.     
  54.     
  55.  
  56. def get_devstudio_versions ():
  57.     """Get list of devstudio versions from the Windows registry.  Return a
  58.        list of strings containing version numbers; the list will be
  59.        empty if we were unable to access the registry (eg. couldn't import
  60.        a registry-access module) or the appropriate registry keys weren't
  61.        found."""
  62.  
  63.     if not _can_read_reg:
  64.         return []
  65.  
  66.     K = 'Software\\Microsoft\\Devstudio'
  67.     L = []
  68.     for base in (HKEY_CLASSES_ROOT,
  69.                  HKEY_LOCAL_MACHINE,
  70.                  HKEY_CURRENT_USER,
  71.                  HKEY_USERS):
  72.         try:
  73.             k = RegOpenKeyEx(base,K)
  74.             i = 0
  75.             while 1:
  76.                 try:
  77.                     p = RegEnumKey(k,i)
  78.                     if p[0] in '123456789' and p not in L:
  79.                         L.append(p)
  80.                 except RegError:
  81.                     break
  82.                 i = i + 1
  83.         except RegError:
  84.             pass
  85.     L.sort()
  86.     L.reverse()
  87.     return L
  88.  
  89. # get_devstudio_versions ()
  90.  
  91.  
  92. def get_msvc_paths (path, version='6.0', platform='x86'):
  93.     """Get a list of devstudio directories (include, lib or path).  Return
  94.        a list of strings; will be empty list if unable to access the
  95.        registry or appropriate registry keys not found."""
  96.        
  97.     if not _can_read_reg:
  98.         return []
  99.  
  100.     L = []
  101.     if path=='lib':
  102.         path= 'Library'
  103.     path = string.upper(path + ' Dirs')
  104.     K = ('Software\\Microsoft\\Devstudio\\%s\\' +
  105.          'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \
  106.         (version,platform)
  107.     for base in (HKEY_CLASSES_ROOT,
  108.                  HKEY_LOCAL_MACHINE,
  109.                  HKEY_CURRENT_USER,
  110.                  HKEY_USERS):
  111.         try:
  112.             k = RegOpenKeyEx(base,K)
  113.             i = 0
  114.             while 1:
  115.                 try:
  116.                     (p,v,t) = RegEnumValue(k,i)
  117.                     if string.upper(p) == path:
  118.                         V = string.split(v,';')
  119.                         for v in V:
  120.                             if v == '' or v in L: continue
  121.                             L.append(v)
  122.                         break
  123.                     i = i + 1
  124.                 except RegError:
  125.                     break
  126.         except RegError:
  127.             pass
  128.     return L
  129.  
  130. # get_msvc_paths()
  131.  
  132.  
  133. def find_exe (exe, version_number):
  134.     """Try to find an MSVC executable program 'exe' (from version
  135.        'version_number' of MSVC) in several places: first, one of the MSVC
  136.        program search paths from the registry; next, the directories in the
  137.        PATH environment variable.  If any of those work, return an absolute
  138.        path that is known to exist.  If none of them work, just return the
  139.        original program name, 'exe'."""
  140.  
  141.     for p in get_msvc_paths ('path', version_number):
  142.         fn = os.path.join (os.path.abspath(p), exe)
  143.         if os.path.isfile(fn):
  144.             return fn
  145.  
  146.     # didn't find it; try existing path
  147.     for p in string.split (os.environ['Path'],';'):
  148.         fn = os.path.join(os.path.abspath(p),exe)
  149.         if os.path.isfile(fn):
  150.             return fn
  151.  
  152.     return exe                          # last desperate hope 
  153.  
  154.  
  155. def set_path_env_var (name, version_number):
  156.     """Set environment variable 'name' to an MSVC path type value obtained
  157.        from 'get_msvc_paths()'.  This is equivalent to a SET command prior
  158.        to execution of spawned commands."""
  159.  
  160.     p = get_msvc_paths (name, version_number)
  161.     if p:
  162.         os.environ[name] = string.join (p,';')
  163.  
  164.  
  165. class MSVCCompiler (CCompiler) :
  166.     """Concrete class that implements an interface to Microsoft Visual C++,
  167.        as defined by the CCompiler abstract class."""
  168.  
  169.     compiler_type = 'msvc'
  170.  
  171.     # Just set this so CCompiler's constructor doesn't barf.  We currently
  172.     # don't use the 'set_executables()' bureaucracy provided by CCompiler,
  173.     # as it really isn't necessary for this sort of single-compiler class.
  174.     # Would be nice to have a consistent interface with UnixCCompiler,
  175.     # though, so it's worth thinking about.
  176.     executables = {}
  177.  
  178.     # Private class data (need to distinguish C from C++ source for compiler)
  179.     _c_extensions = ['.c']
  180.     _cpp_extensions = ['.cc','.cpp']
  181.  
  182.     # Needed for the filename generation methods provided by the
  183.     # base class, CCompiler.
  184.     src_extensions = _c_extensions + _cpp_extensions
  185.     obj_extension = '.obj'
  186.     static_lib_extension = '.lib'
  187.     shared_lib_extension = '.dll'
  188.     static_lib_format = shared_lib_format = '%s%s'
  189.     exe_extension = '.exe'
  190.  
  191.  
  192.     def __init__ (self,
  193.                   verbose=0,
  194.                   dry_run=0,
  195.                   force=0):
  196.  
  197.         CCompiler.__init__ (self, verbose, dry_run, force)
  198.         versions = get_devstudio_versions ()
  199.  
  200.         if versions:
  201.             version = versions[0]  # highest version
  202.  
  203.             self.cc   = find_exe("cl.exe", version)
  204.             self.link = find_exe("link.exe", version)
  205.             self.lib  = find_exe("lib.exe", version)
  206.             set_path_env_var ('lib', version)
  207.             set_path_env_var ('include', version)
  208.             path=get_msvc_paths('path', version)
  209.             try:
  210.                 for p in string.split(os.environ['path'],';'):
  211.                     path.append(p)
  212.             except KeyError:
  213.                 pass
  214.             os.environ['path'] = string.join(path,';')
  215.         else:
  216.             # devstudio not found in the registry
  217.             self.cc = "cl.exe"
  218.             self.link = "link.exe"
  219.             self.lib = "lib.exe"
  220.  
  221.         self.preprocess_options = None
  222.         self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3' ]
  223.         self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/Z7', '/D_DEBUG']
  224.  
  225.         self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
  226.         self.ldflags_shared_debug = [
  227.             '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG'
  228.             ]
  229.         self.ldflags_static = [ '/nologo']
  230.  
  231.  
  232.     # -- Worker methods ------------------------------------------------
  233.  
  234.     def compile (self,
  235.                  sources,
  236.                  output_dir=None,
  237.                  macros=None,
  238.                  include_dirs=None,
  239.                  debug=0,
  240.                  extra_preargs=None,
  241.                  extra_postargs=None):
  242.  
  243.         (output_dir, macros, include_dirs) = \
  244.             self._fix_compile_args (output_dir, macros, include_dirs)
  245.         (objects, skip_sources) = self._prep_compile (sources, output_dir)
  246.  
  247.         if extra_postargs is None:
  248.             extra_postargs = []
  249.  
  250.         pp_opts = gen_preprocess_options (macros, include_dirs)
  251.         compile_opts = extra_preargs or []
  252.         compile_opts.append ('/c')
  253.         if debug:
  254.             compile_opts.extend (self.compile_options_debug)
  255.         else:
  256.             compile_opts.extend (self.compile_options)
  257.         
  258.         for i in range (len (sources)):
  259.             src = sources[i] ; obj = objects[i]
  260.             ext = (os.path.splitext (src))[1]
  261.  
  262.             if skip_sources[src]:
  263.                 self.announce ("skipping %s (%s up-to-date)" % (src, obj))
  264.             else:
  265.                 if ext in self._c_extensions:
  266.                     input_opt = "/Tc" + src
  267.                 elif ext in self._cpp_extensions:
  268.                     input_opt = "/Tp" + src
  269.  
  270.                 output_opt = "/Fo" + obj
  271.  
  272.                 self.mkpath (os.path.dirname (obj))
  273.                 try:
  274.                     self.spawn ([self.cc] + compile_opts + pp_opts +
  275.                                 [input_opt, output_opt] +
  276.                                 extra_postargs)
  277.                 except DistutilsExecError, msg:
  278.                     raise CompileError, msg
  279.  
  280.         return objects
  281.  
  282.     # compile ()
  283.  
  284.  
  285.     def create_static_lib (self,
  286.                            objects,
  287.                            output_libname,
  288.                            output_dir=None,
  289.                            debug=0,
  290.                            extra_preargs=None,
  291.                            extra_postargs=None):
  292.  
  293.         (objects, output_dir) = self._fix_object_args (objects, output_dir)
  294.         output_filename = \
  295.             self.library_filename (output_libname, output_dir=output_dir)
  296.  
  297.         if self._need_link (objects, output_filename):
  298.             lib_args = objects + ['/OUT:' + output_filename]
  299.             if debug:
  300.                 pass                    # XXX what goes here?
  301.             if extra_preargs:
  302.                 lib_args[:0] = extra_preargs
  303.             if extra_postargs:
  304.                 lib_args.extend (extra_postargs)
  305.             try:
  306.                 self.spawn ([self.lib] + lib_args)
  307.             except DistutilsExecError, msg:
  308.                 raise LibError, msg
  309.                 
  310.         else:
  311.             self.announce ("skipping %s (up-to-date)" % output_filename)
  312.  
  313.     # create_static_lib ()
  314.     
  315.  
  316.     def link_shared_lib (self,
  317.                          objects,
  318.                          output_libname,
  319.                          output_dir=None,
  320.                          libraries=None,
  321.                          library_dirs=None,
  322.                          runtime_library_dirs=None,
  323.                          export_symbols=None,
  324.                          debug=0,
  325.                          extra_preargs=None,
  326.                          extra_postargs=None,
  327.                          build_temp=None):
  328.  
  329.         self.link_shared_object (objects,
  330.                                  self.shared_library_name(output_libname),
  331.                                  output_dir=output_dir,
  332.                                  libraries=libraries,
  333.                                  library_dirs=library_dirs,
  334.                                  runtime_library_dirs=runtime_library_dirs,
  335.                                  export_symbols=export_symbols,
  336.                                  debug=debug,
  337.                                  extra_preargs=extra_preargs,
  338.                                  extra_postargs=extra_postargs,
  339.                                  build_temp=build_temp)
  340.                     
  341.     
  342.     def link_shared_object (self,
  343.                             objects,
  344.                             output_filename,
  345.                             output_dir=None,
  346.                             libraries=None,
  347.                             library_dirs=None,
  348.                             runtime_library_dirs=None,
  349.                             export_symbols=None,
  350.                             debug=0,
  351.                             extra_preargs=None,
  352.                             extra_postargs=None,
  353.                             build_temp=None):
  354.  
  355.         (objects, output_dir) = self._fix_object_args (objects, output_dir)
  356.         (libraries, library_dirs, runtime_library_dirs) = \
  357.             self._fix_lib_args (libraries, library_dirs, runtime_library_dirs)
  358.  
  359.         if runtime_library_dirs:
  360.             self.warn ("I don't know what to do with 'runtime_library_dirs': "
  361.                        + str (runtime_library_dirs))
  362.         
  363.         lib_opts = gen_lib_options (self,
  364.                                     library_dirs, runtime_library_dirs,
  365.                                     libraries)
  366.         if output_dir is not None:
  367.             output_filename = os.path.join (output_dir, output_filename)
  368.  
  369.         if self._need_link (objects, output_filename):
  370.  
  371.             if debug:
  372.                 ldflags = self.ldflags_shared_debug
  373.             else:
  374.                 ldflags = self.ldflags_shared
  375.  
  376.             export_opts = []
  377.             for sym in (export_symbols or []):
  378.                 export_opts.append("/EXPORT:" + sym)
  379.  
  380.             ld_args = (ldflags + lib_opts + export_opts + 
  381.                        objects + ['/OUT:' + output_filename])
  382.  
  383.             # The MSVC linker generates .lib and .exp files, which cannot be
  384.             # suppressed by any linker switches. The .lib files may even be
  385.             # needed! Make sure they are generated in the temporary build
  386.             # directory. Since they have different names for debug and release
  387.             # builds, they can go into the same directory.
  388.             (dll_name, dll_ext) = os.path.splitext(
  389.                 os.path.basename(output_filename))
  390.             implib_file = os.path.join(
  391.                 os.path.dirname(objects[0]),
  392.                 self.library_filename(dll_name))
  393.             ld_args.append ('/IMPLIB:' + implib_file)
  394.  
  395.             if extra_preargs:
  396.                 ld_args[:0] = extra_preargs
  397.             if extra_postargs:
  398.                 ld_args.extend(extra_postargs)
  399.  
  400.             self.mkpath (os.path.dirname (output_filename))
  401.             try:
  402.                 self.spawn ([self.link] + ld_args)
  403.             except DistutilsExecError, msg:
  404.                 raise LinkError, msg
  405.  
  406.         else:
  407.             self.announce ("skipping %s (up-to-date)" % output_filename)
  408.  
  409.     # link_shared_object ()
  410.  
  411.  
  412.     def link_executable (self,
  413.                          objects,
  414.                          output_progname,
  415.                          output_dir=None,
  416.                          libraries=None,
  417.                          library_dirs=None,
  418.                          runtime_library_dirs=None,
  419.                          debug=0,
  420.                          extra_preargs=None,
  421.                          extra_postargs=None):
  422.  
  423.         (objects, output_dir) = self._fix_object_args (objects, output_dir)
  424.         (libraries, library_dirs, runtime_library_dirs) = \
  425.             self._fix_lib_args (libraries, library_dirs, runtime_library_dirs)
  426.  
  427.         if runtime_library_dirs:
  428.             self.warn ("I don't know what to do with 'runtime_library_dirs': "
  429.                        + str (runtime_library_dirs))
  430.         
  431.         lib_opts = gen_lib_options (self,
  432.                                     library_dirs, runtime_library_dirs,
  433.                                     libraries)
  434.         output_filename = output_progname + self.exe_extension
  435.         if output_dir is not None:
  436.             output_filename = os.path.join (output_dir, output_filename)
  437.  
  438.         if self._need_link (objects, output_filename):
  439.  
  440.             if debug:
  441.                 ldflags = self.ldflags_shared_debug[1:]
  442.             else:
  443.                 ldflags = self.ldflags_shared[1:]
  444.  
  445.             ld_args = ldflags + lib_opts + \
  446.                       objects + ['/OUT:' + output_filename]
  447.  
  448.             if extra_preargs:
  449.                 ld_args[:0] = extra_preargs
  450.             if extra_postargs:
  451.                 ld_args.extend (extra_postargs)
  452.  
  453.             self.mkpath (os.path.dirname (output_filename))
  454.             try:
  455.                 self.spawn ([self.link] + ld_args)
  456.             except DistutilsExecError, msg:
  457.                 raise LinkError, msg
  458.         else:
  459.             self.announce ("skipping %s (up-to-date)" % output_filename)   
  460.     
  461.  
  462.     # -- Miscellaneous methods -----------------------------------------
  463.     # These are all used by the 'gen_lib_options() function, in
  464.     # ccompiler.py.
  465.  
  466.     def library_dir_option (self, dir):
  467.         return "/LIBPATH:" + dir
  468.  
  469.     def runtime_library_dir_option (self, dir):
  470.         raise DistutilsPlatformError, \
  471.               "don't know how to set runtime library search path for MSVC++"
  472.  
  473.     def library_option (self, lib):
  474.         return self.library_filename (lib)
  475.  
  476.  
  477.     def find_library_file (self, dirs, lib, debug=0):
  478.         # Prefer a debugging library if found (and requested), but deal
  479.         # with it if we don't have one.
  480.         if debug:
  481.             try_names = [lib + "_d", lib]
  482.         else:
  483.             try_names = [lib]
  484.         for dir in dirs:
  485.             for name in try_names:
  486.                 libfile = os.path.join(dir, self.library_filename (name))
  487.                 if os.path.exists(libfile):
  488.                     return libfile
  489.         else:
  490.             # Oops, didn't find it in *any* of 'dirs'
  491.             return None
  492.  
  493.     # find_library_file ()
  494.  
  495. # class MSVCCompiler
  496.